<?
class BackupsComponent extends Object {

	var $name = 'Backups';

	var $components = array('Mailer');

	var $log_filename = 'backup';

	/**
	 * Requires MySQL
	 *
	 * @param compress file will be compressed with gzip
	 * @param email If an email address is supplied, the file will be emailed and then deleted, otherwise it will remin on the filesystem
	 *
	 * @return false if the backup failed, true otherwise
	 */
	function backup($compress = true, $email = null) {

		ini_set("memory_limit","128M");

		// Perform backup
		$filename = TMP . date('Ymd-Hi') . ".sql";

		App::Import('ConnectionManager');
		$ds = ConnectionManager::getDataSource('default');
		$dsc = $ds->config;

		$command = "mysqldump -u {$dsc['login']} --password={$dsc['password']} {$dsc['database']} > {$filename}";
		$this->log($command);

		$result = exec($command, $output, $return_code);

		if ($return_code != 0) {
			$this->log('exec command failed for : '.$command);
			$this->log($return_code);
			return false;
		} else {

			if ($compress) {
				exec("gzip $filename");
				$filename .= ".gz";
			}

			// Send backup
			if (!is_null($email)) {

				$date = date('d/m/Y');
				$filesize = number_format(filesize($filename) / 1048576, 0);

				$m = $this->Mailer;
		/*
				$m->IsSMTP(true);
				$m->SMTPAuth = true;
				$m->Username = 'username@gmail.com';
				$m->Password = 'password';
				$m->Host = 'ssl://smtp.gmail.com:465';
		*/
				$m->FromName = 'eboCash Backup Mailer';
				$m->AddAddress($email);
				$m->AddAttachment($filename);
				$m->Subject = "Database Backup - $date";
				$m->Body = "The Database Backup for {$date} is attached, the filesize is: {$filesize}MB.";

				if ($m->Send()) {
				   $this->log("Success");
				   unlink($filename);
				   return true;
				} else {
				   $this->log("Error, could not send: {$m->ErrorInfo}");
				   return false;
				}
			} else {
				return true;
			}

		}


	}

}
?>